import { makeAutoObservable } from 'mobx';
import { isEmpty, isObject } from 'esy-ui';
import { createContext, useContext } from 'react';
import { lsGetJsonItem, lsSetJsonItem } from '@/utils/localStorage';

// 当前 class 类中的全局变量
export interface UserInfoStateType {
  token: string;
  name: string;
  id: number;
  age: number;
  birthday: string;
  loginTime?: string;
  nickname?: string;
  realname?: string;
  faceId?: number;
}

export class UserInfoState {
  constructor() {
    makeAutoObservable(this);
    this.clearUserInfo = this.clearUserInfo.bind(this);
    this.changeLocalMobx = this.changeLocalMobx.bind(this);
    this.changeUserInfo = this.changeUserInfo.bind(this);
    this.changeLocalMobx();
  }

  // 用户信息
  userInfo: Partial<UserInfoStateType> | null = null;

  // 保存用户信息
  changeUserInfo(info?: Partial<UserInfoStateType>) {
    if (isObject(info) && !isEmpty(info)) {
      if (this.userInfo) {
        this.userInfo = { ...this.userInfo, ...info };
        lsSetJsonItem('userInfo', { ...this.userInfo, ...info });
      } else {
        this.userInfo = { ...info };
        lsSetJsonItem('userInfo', { ...info });
      }
    }
  }

  // 清除所有数据
  clearUserInfo() {
    lsSetJsonItem('userInfo', null);
    this.userInfo = null;
  }

  // 自动补充用户信息
  changeLocalMobx() {
    const userInfo = lsGetJsonItem('userInfo') || {};
    // 如果已经有值就保存起来
    if (userInfo?.token) {
      this.changeUserInfo(userInfo);
    }
  }
}

// 利用createContext 创建storeContext
export const storeUserInfo = createContext(new UserInfoState());

// 导出一个hook 获取全局state的变量值
export const useUserInfoStore = () => useContext(storeUserInfo);
